package test.yzx.pproject.view;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;


public class PathMeasureView extends View{


    public PathMeasureView(Context context) {
        super(context);
    }
    public PathMeasureView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }
    public PathMeasureView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    private Path fullPath = new Path();
    private Path animPath = new Path();
    private PathMeasure pm = new PathMeasure();
    private float animProgress = 0f;
    private RectF fullRect = new RectF();
    private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    {
    }


    private RectF clipRect = new RectF();
    @Override
    protected void onDraw(Canvas canvas) {
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(10);
        paint.setColor(Color.RED);
        float halfStrokeWidth = paint.getStrokeWidth()/2;

        clipRect.set(0,0,getWidth()-paint.getStrokeWidth()*2, getHeight());
        canvas.clipRect(clipRect);

        fullRect.set(halfStrokeWidth, halfStrokeWidth, getWidth()-halfStrokeWidth, getHeight()-halfStrokeWidth);
        fullPath.reset();
        fullPath.addRoundRect(fullRect, 10, 10, Path.Direction.CW);
        pm.setPath(fullPath, false);

        animPath.reset();
        float end = pm.getLength()*animProgress;
        float start = end - getWidth();
        pm.getSegment(start, end, animPath, true);
        canvas.drawPath(animPath, paint);
    }


    public void start(){
        post(new Runnable() {
            public void run() {
                ValueAnimator anim = ValueAnimator.ofFloat(0f, 1.5f).setDuration(2500);
                anim.setInterpolator(new LinearInterpolator());
                anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    public void onAnimationUpdate(ValueAnimator animation) {
                        animProgress = (float) animation.getAnimatedValue();
                        invalidate();
                    }});
                anim.setRepeatCount(ValueAnimator.INFINITE);
                anim.start();
            }
        });
    }

}
